package com.leyou.item.service;


import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;//IDEA报错实际可以

    /**
     * 查询类别由通过pid
     *
     * @param pid pid
     * @return {@link List}<{@link Category}>
     */
    public List<Category> queryCategoriesByPid(Long pid) {
        Category category = new Category();
        category.setParentId(pid);//根据父目录查询
        return this.categoryMapper.select(category);
    }

    /**
     * 查询名称由id-商品列表展示辅助类
     *
     * @param ids id
     * @return {@link List}<{@link String}>
     */
    public List<String> queryNamesByIds(List<Long> ids) {
        List<Category> categories = this.categoryMapper.selectByIdList(ids);//ids-cats主键集合查询实体集合
//        //集合转换
//        List<String> names = new ArrayList<>();
//        for (Category category : categories) {
//            names.add(category.getName());
//        }
//        return names;
        //流，；lambda 一行解决
        return categories.stream().map(category -> category.getName()).collect(Collectors.toList());
    }

    /**
     * 查询所有分类根据cid3
     *
     * @param id id
     */
    public List<Category> queryAllByCid3(Long id) {

        //select 出来的是某个集合，现在要的是具体的对象，如何获取父（子）id成为集合
        Category cid3 = this.categoryMapper.selectByPrimaryKey(id);
        Category cid2 = this.categoryMapper.selectByPrimaryKey(cid3.getParentId());
        Category cid1 = this.categoryMapper.selectByPrimaryKey(cid2.getParentId());

        return Arrays.asList(cid1, cid2, cid3);
    }
}
